package ipdesk.model.businessInfo.dao;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.ibatis.dao.client.DaoManager;
import com.opensymphony.xwork2.ActionContext;


import ipdesk.common.Codes;
import ipdesk.model.businessInfo.bean.BusinessCustomerInfoBean;
import ipdesk.model.businessInfo.bean.BusinessInfoBean;
import ipdesk.model.report.promote.bean.PromoteInfoBean;
import ipdesk.model.user.dao.IUser;

import ecg.dao.DaoService;
import ecg.util.SqlMapLocator;
import ecg.util.Time;
import ecg.util.bean.PageDataBean;



public class BusinessInfoDao
{
	private static BusinessInfoDao singleton;
		
		
	public static BusinessInfoDao getInstance()
	{
		if(singleton == null)
		{
			singleton = new BusinessInfoDao();
		}
		
		return singleton;
	}
	
	private DaoManager	manager	= DaoService.getInstance();
	private IBusinessInfo businessInfo 	= (IBusinessInfo)manager.getDao(IBusinessInfo.class, "ip_desk");
	
	ActionContext context = ActionContext.getContext();
	Map<String, String> session = (Map<String, String>)context.getSession();
	
	
	
	/**
	 * 기업 정보 등록
	 * @param businessInfoBean
	 * @return
	 * @throws Exception
	 */
	public int businessInfoReg(BusinessInfoBean businessInfoBean) throws Exception
	{
		int lastCompanySeq = 0;
		
		
		//String localBizNo = businessInfoBean.getLocalBizNo1() + "-" + businessInfoBean.getLocalBizNo2() + "-" + businessInfoBean.getLocalBizNo3();
		//businessInfoBean.setLocalBizNo(localBizNo);
		
		String headBizNo = businessInfoBean.getHeadBizNo1() + "-" + businessInfoBean.getHeadBizNo2() + "-" + businessInfoBean.getHeadBizNo3();
		businessInfoBean.setHeadBizNo(headBizNo);
		
		/*String telNo = "";
		
		String telNo1 = businessInfoBean.getTelNo1();
		String telNo2 = businessInfoBean.getTelNo2();
		String telNo3 = businessInfoBean.getTelNo3();
		
		if(!telNo1.equals("") && !telNo2.equals("") && !telNo3.equals(""))
		{
			telNo = telNo1 + "-" + telNo2 + "-" + telNo3;
		}
		
		businessInfoBean.setTelNo(telNo);
		
		String mobileNo = businessInfoBean.getMobileNo1() + "-" + businessInfoBean.getMobileNo2() + "-" + businessInfoBean.getMobileNo3();
		businessInfoBean.setMobileNo(mobileNo);
		
		String faxNo = "";
		
		String faxNo1 = businessInfoBean.getFaxNo1();
		String faxNo2 = businessInfoBean.getFaxNo2();
		String faxNo3 = businessInfoBean.getFaxNo3();
		
		if(!faxNo1.equals("") && !faxNo2.equals("") && !faxNo3.equals(""))
		{
			faxNo = faxNo1 + "-" + faxNo2 + "-" + faxNo3;
		}
		
		businessInfoBean.setFaxNo(faxNo);*/
		
		String email = businessInfoBean.getEmail1() + "@" + businessInfoBean.getEmail2();
		businessInfoBean.setEmail(email);
		
		try{
			// 트랜잭션 시작
			manager.startTransaction();
			
			
			
			// 기업정보 insert.
			lastCompanySeq = businessInfo.businessInfoReg(businessInfoBean);
			
			if(lastCompanySeq != 0)
			{
				// 상담자정보 insert.
				
				// 마지막에 insert된 기업정보 데이터의 company_seq를 빈 객체에 저장.
				businessInfoBean.setCompanySeq(lastCompanySeq);
			
				// 3.  상담을 의뢰한 담당자 정보 insert.
				businessInfo.bizCustomerInfoReg(businessInfoBean);
			}
			manager.commitTransaction();
		}finally{
			manager.endTransaction();
		}
		
		return lastCompanySeq;
		
		
	}
	
	// 로그인한 사용자의  해당 센터의 등록된 기업정보를 가져오는 메서드.
	public List<BusinessInfoBean> getAllListForUser(BusinessInfoBean businessInfoBean) throws SQLException
	{
		List<BusinessInfoBean> list = SqlMapLocator.getMapper().queryForList("select-all-for-user", businessInfoBean.getUserSeq());
		
		return list;
	}
	
	// 로그인한 사용자에 해당하는 등록된 기업정보의 담당자 정보를 가져오는 메서드.
	public List<BusinessCustomerInfoBean> getAllCustomerListForCompany(int companySeq) throws SQLException
	{
		List<BusinessCustomerInfoBean> list = businessInfo.getAllCustomerListForCompany(companySeq);
		
		
		return list;
	}
	
	
	/**
	 * 센터에 해당하는 회사와 담당자를 선택하는 팝업창에서 사용됨.
	 */
	// 선택한 센터를 조건으로 하는 로우를 가져오는 메서드.
	public List getCompanyList(String deskCode) throws SQLException
	{
		List list = businessInfo.getCompanyList(deskCode);
		
		return list;
	}
	
	// 선택한 회사를 조건으로 하는 담당자 로우를 가져오는 메서드.
	public List getCustomerList(int companySeq) throws SQLException
	{
		List list = businessInfo.getCustomerList(companySeq);
		
		return list;
	}
	
	
	public int getDataTotalCount(BusinessInfoBean businessInfoBean) throws Exception
	{
		int totalDataCount = businessInfo.getDataTotalCount(businessInfoBean);
		
		return totalDataCount;
	}
	
	
	public List<BusinessInfoBean> getPagingDataListForUser(Map map) throws Exception
	{
		
		List<BusinessInfoBean> pageDataList = businessInfo.getPagingDataListForUser(map);
			
		return pageDataList;
	}
	
	/**
	 *  해당 companySeq에 대한 데이터를 가지고 온다.
	 *
	 */
	public BusinessInfoBean getDetailData(int  companySeq)
	{
		BusinessInfoBean businessInfoBean = businessInfo.getDataOneRow( companySeq, "biz.companyDetailData");
		
		// 시간 잘라내기
		String modTime = businessInfoBean.getModifyTime();
		
		String localDivisionCodeValue = Codes.getInstance().getLocalDivisionCode(businessInfoBean.getLocalDivisionCode());
		businessInfoBean.setLocalDivisionCode(localDivisionCodeValue);
		
		String headSizeCodeCodeValue = Codes.getInstance().getHeadSizeCode(businessInfoBean.getHeadSizeCode());
		businessInfoBean.setHeadSizeCode(headSizeCodeCodeValue);
		
		if(modTime != null && (!modTime.equals("")))
		{
			String modifyTime = businessInfoBean.getModifyTime().substring(0, 10);
			
			// 변환된 스트링을 다시 빈에 저장.
			businessInfoBean.setModifyTime(modifyTime);
		}
		
		return businessInfoBean;
	}
	
	/**
	 *  해당 companySeq에 대한 데이터를 가지고 온다.
	 *
	 */
	public BusinessInfoBean getModifyData(int companySeq)
	{
		BusinessInfoBean businessInfoBean = businessInfo.getDataOneRow(companySeq, "biz.companyDetailData");
		
		String[] localBizNO = businessInfoBean.getLocalBizNo().split("-");
		
		/*if(localBizNO.length == 3)
		{
			businessInfoBean.setLocalBizNo1(localBizNO[0]);
			businessInfoBean.setLocalBizNo2(localBizNO[1]);
			businessInfoBean.setLocalBizNo3(localBizNO[2]);
		}*/
		
		// 현지기업 구분 코드를 심플코드로 변환.
		String localDivisionCodeSimple = Codes.getInstance().getFromLocalDivisionCodeToSimpleCode(businessInfoBean.getLocalDivisionCode());
		businessInfoBean.setLocalDivisionCode(localDivisionCodeSimple);
		
		String[] headBizNo = businessInfoBean.getHeadBizNo().split("-");
		
		if(headBizNo.length ==3)
		{
			businessInfoBean.setHeadBizNo1(headBizNo[0]);
			businessInfoBean.setHeadBizNo2(headBizNo[1]);
			businessInfoBean.setHeadBizNo3(headBizNo[2]);
		}
		// 본사기업 규모의 구분 코드를 심플코드로 변환.
		String headSizeCodeSimple = Codes.getInstance().getFromHeadSizeCodeToSimpleCode(businessInfoBean.getHeadSizeCode());
		businessInfoBean.setHeadSizeCode(headSizeCodeSimple);
		
		return businessInfoBean;
	}
	
	/**
	 * 해당 기업 정보의 수정 처리
	 */
	public int companyUpdate(BusinessInfoBean businessInfoBean)
	{
		int result = 0;
		
		//String localBizNo = businessInfoBean.getLocalBizNo1() + "-" + businessInfoBean.getLocalBizNo2() + "-" + businessInfoBean.getLocalBizNo3();
		//businessInfoBean.setLocalBizNo(localBizNo);
		
		String headBizNo = businessInfoBean.getHeadBizNo1() + "-" + businessInfoBean.getHeadBizNo2() + "-" + businessInfoBean.getHeadBizNo3();
		businessInfoBean.setHeadBizNo(headBizNo);
		
		// 현지기업 심플코드를 원래코드로 변환.
		String localDivisionCode = Codes.getInstance().getFromSimpleCodeToLocalDivisionCode(businessInfoBean.getLocalDivisionCode());
		businessInfoBean.setLocalDivisionCode(localDivisionCode);
		
		// 본사기업 규모의 심플코드를 원래 코드로 변환.
		String headSizeCode = Codes.getInstance().getFromSimpleCodeToHeadSizeCode(businessInfoBean.getHeadSizeCode());
		businessInfoBean.setHeadSizeCode(headSizeCode);
		
		try{
			manager.startTransaction();
			
			// 기업정보 업데이트.
			result = businessInfo.companyUpdate(businessInfoBean, "biz.updateCompanyData");
			
			manager.commitTransaction();
			
		}finally{
			manager.endTransaction();
		}
		
		
		return result;
	}
	
	/**
	 * 기업정보의 삭제
	 */
	public void bizCompanyInfoDelete(BusinessInfoBean businessInfoBean)
	{
		/**
		 * 담당자 정보 삭제후, 기업정보 삭제
		 */
		try{
			manager.startTransaction();
			
			// 해당 기업의 전체 담당자 정보 삭제
			businessInfo.bizCustomerInfoDelete(businessInfoBean, "biz.deleteMultiCustomerData");
			
			// 해당 기업 정보 삭제
			businessInfo.bizCompanyInfoDelete(businessInfoBean, "biz.deleteCompanyData");
			
			manager.commitTransaction();
		}finally{
			manager.endTransaction();
		}
	}
	
	/**
	 * 해당 기업의 담당자 정보 등록
	 */
	public void bizCustomerInfoReg(BusinessInfoBean businessInfoBean)
	{
		String regTime = Time.getYearMonthDayWithDash();
		businessInfoBean.setRegTime(regTime);
		
		/*String telNo = "";
		
		String telNo1 = businessInfoBean.getTelNo1();
		String telNo2 = businessInfoBean.getTelNo2();
		String telNo3 = businessInfoBean.getTelNo3();
		
		if(!telNo1.equals("") && !telNo2.equals("") && !telNo3.equals(""))
		{
			telNo = telNo1 + "-" + telNo2 + "-" + telNo3;
		}
		
		businessInfoBean.setTelNo(telNo);
		
		String mobileNo = businessInfoBean.getMobileNo1() + "-" + businessInfoBean.getMobileNo2() + "-" + businessInfoBean.getMobileNo3();
		businessInfoBean.setMobileNo(mobileNo);
		*/
		String faxNo = "";
		
		String faxNo1 = businessInfoBean.getFaxNo1();
		String faxNo2 = businessInfoBean.getFaxNo2();
		String faxNo3 = businessInfoBean.getFaxNo3();
		
		if(!faxNo1.equals("") && !faxNo2.equals("") && !faxNo3.equals(""))
		{
			faxNo = faxNo1 + "-" + faxNo2 + "-" + faxNo3;
		}
		
		businessInfoBean.setFaxNo(faxNo);
		
		String email = businessInfoBean.getEmail1() + "@" + businessInfoBean.getEmail2();
		businessInfoBean.setEmail(email);
		
		
		try{
			manager.startTransaction();
			
			businessInfo.bizCustomerInfoReg(businessInfoBean);
			
			manager.commitTransaction();
		}finally{
			manager.endTransaction();
		}
	}
	
	
	/**
	 *  해당 customerSeq에 대한 담당자 데이터를 가지고 온다.
	 *
	 */
	public BusinessInfoBean getModifyCustomerData(int customerSeq)
	{
		BusinessInfoBean customerInfoBean = businessInfo.getDataOneRow(customerSeq, "biz.customerDetailData");
		
	//	String[] telNo = customerInfoBean.getTelNo().split("-");
	//	String[] mobileNo = customerInfoBean.getMobileNo().split("-");
		String[] faxNo = customerInfoBean.getFaxNo().split("-");
		String[] email = customerInfoBean.getEmail().split("@");
		
	/*	if(telNo.length == 3)
		{
			customerInfoBean.setTelNo1(telNo[0]);
			customerInfoBean.setTelNo2(telNo[1]);
			customerInfoBean.setTelNo3(telNo[2]);
		}
	
		if(mobileNo.length == 3)
		{
			customerInfoBean.setMobileNo1(mobileNo[0]);
			customerInfoBean.setMobileNo2(mobileNo[1]);
			customerInfoBean.setMobileNo3(mobileNo[2]);
		}
		*/
		if(faxNo.length == 3)
		{
			customerInfoBean.setFaxNo1(faxNo[0]);
			customerInfoBean.setFaxNo2(faxNo[1]);
			customerInfoBean.setFaxNo3(faxNo[2]);
		}
		
		if(email.length == 2)
		{
			customerInfoBean.setEmail1(email[0]);
			customerInfoBean.setEmail2(email[1]);
		}
		
		// 상담경로 값을 심플코드로 변환.
		String consultingCodeSimple = Codes.getInstance().getFromConsultingCodeValueToSimpleCode(customerInfoBean.getConsultingCode());
		customerInfoBean.setConsultingCode(consultingCodeSimple);
		
	
				
		// 전담유무 플래그 값을 심플코드로 변환.
		String exclusiveFlagCodeSimple = Codes.getInstance().getFromExclusiveFlagCodeValueToSimpleCode(customerInfoBean.getExclusiveFlag());
		customerInfoBean.setExclusiveFlag(exclusiveFlagCodeSimple);
		
		
		return customerInfoBean;
	}
	
	/**
	 * 담당자 정보 수정 처리
	 * @param businessInfoBean
	 */
	public void bizCustomerInfoUpdate(BusinessInfoBean businessInfoBean)
	{
		String modifyTime = Time.getYearMonthDayWithDash();
		businessInfoBean.setModifyTime(modifyTime);
		
	/*	String telNo = "";
		
		String telNo1 = businessInfoBean.getTelNo1();
		String telNo2 = businessInfoBean.getTelNo2();
		String telNo3 = businessInfoBean.getTelNo3();
		
		if(!telNo1.equals("") && !telNo2.equals("") && !telNo3.equals(""))
		{
			telNo = telNo1 + "-" + telNo2 + "-" + telNo3;
		}
		
		businessInfoBean.setTelNo(telNo);
		
		String mobileNo = businessInfoBean.getMobileNo1() + "-" + businessInfoBean.getMobileNo2() + "-" + businessInfoBean.getMobileNo3();
		businessInfoBean.setMobileNo(mobileNo);*/
		
		String faxNo = "";
		
		String faxNo1 = businessInfoBean.getFaxNo1();
		String faxNo2 = businessInfoBean.getFaxNo2();
		String faxNo3 = businessInfoBean.getFaxNo3();
		
		if(!faxNo1.equals("") && !faxNo2.equals("") && !faxNo3.equals(""))
		{
			faxNo = faxNo1 + "-" + faxNo2 + "-" + faxNo3;
		}
		
		businessInfoBean.setFaxNo(faxNo);
		
		String email = businessInfoBean.getEmail1() + "@" + businessInfoBean.getEmail2();
		businessInfoBean.setEmail(email);
		
		// 상담경로 심플코드를 원래코드로 변환.
		String consultingCode = Codes.getInstance().getFromSimpleCodeToConsultingCode(businessInfoBean.getConsultingCode());
		businessInfoBean.setConsultingCode(consultingCode);
		
	
				
		// 전담유무 플래그 심플코드를 원래코드로 변환.
		String exclusiveFlagCode = Codes.getInstance().getFromSimpleCodeToExclusiveFlagCode(businessInfoBean.getExclusiveFlag());
		businessInfoBean.setExclusiveFlag(exclusiveFlagCode);
		
		try{
			manager.startTransaction();
			
			businessInfo.bizCustomerInfoUpdate(businessInfoBean, "biz.updateCustomerData");
			
			manager.commitTransaction();
		}finally{
			manager.endTransaction();
		}
	}
	
	/**
	 * 담당자 정보 삭제
	 * @param customerSeq
	 */
	public void bizCustomerInfoDelete(BusinessInfoBean businessInfoBean)
	{
		try{
			manager.startTransaction();
			
			businessInfo.bizCustomerInfoDelete(businessInfoBean, "biz.deleteCustomerData");
			
			manager.commitTransaction();
		}finally{
			manager.endTransaction();
		}
	}
	
	/**
	 * 회사명 검색
	 * @param searchKeyword
	 * @return
	 */
	public List<BusinessInfoBean> getSearchCompany(String searchKeyword, String agentFlag)  {
		BusinessInfoBean businessInfoBean = new BusinessInfoBean();
		businessInfoBean.setSearchKeyword(searchKeyword);
		businessInfoBean.setAgentFlag(agentFlag);
		
		return businessInfo.getSearchCompany(businessInfoBean);
	}
	
	/**
	 * 회사명 검색 수 
	 * @param searchKeyword
	 * @return
	 */
	public int getSearchCount(String searchKeyword) {
		BusinessInfoBean businessInfoBean = new BusinessInfoBean();
		businessInfoBean.setSearchKeyword(searchKeyword);
		
		return businessInfo.getSearchCount(businessInfoBean);
	}
	
	/**
	 * 현지업체명 중복 확인
	 * @param businessInfoBean
	 * @return
	 */
	public int checkHeadName(String headName) {
		BusinessInfoBean businessInfoBean = new BusinessInfoBean();
		businessInfoBean.setHeadName(headName);
		
		return (Integer)businessInfo.checkHeadName(businessInfoBean);
	}
	
}
